class TapManager {
  private static _instance: TapManager;

  constructor() {
    Logger.assert(!TapManager._instance, "Create tap manager multiple times");
  }

  public static get instance(): TapManager {
    if (!TapManager._instance) {
      TapManager._instance = new TapManager();
    }

    return TapManager._instance;
  }

  private guiLayer: GuiLayer;
  private lockList: any[] = [];
  init(guiLayer: GuiLayer): boolean {
    this.guiLayer = guiLayer;
    guiLayer.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap, this, true);
    return true;
  }

  onTap(e: egret.TouchEvent) {
    if (this.lockList.length > 0 && !!e.target) {
      if (this.lockList.indexOf(e.target) >= 0) {
        e.stopPropagation();
        return;
      } else {
        let p = (e.target as egret.DisplayObject).parent;
        while (!!p) {
          if (this.lockList.indexOf(e.target) >= 0) {
            e.stopPropagation();
            return;
          }
          p = p.parent;
        }
      }
    }
  }

  public lock(obj: any) {
    if (!obj)
      return;
    if (this.lockList.indexOf(obj) < 0) {
      this.lockList.push(obj);
    }
  }

  public unlock(obj: any) {
    if (!obj)
      return;
    let index = this.lockList.indexOf(obj);
    if (index >= 0) {
      this.lockList.splice(index, 1);
    }
  }

  public bind(obj: any, p: Promise<any>) {
    this.lock(obj);
    p.then(() => { this.unlock(obj); });
    p.catch(() => { this.unlock(obj); });
  }
}